// CDN 源类型
export enum CdnSource {
  Cdnjs = 'cdnjs.cloudflare.com',
  Jsdelivr = 'jsdelivr.net',
  Unpkg = 'unpkg.com',
  Custom = 'custom',
}

// 依赖库类型
export enum ExternalDependency {
  JQuery = 'jquery',
  SweetAlert = 'sweetalert',
  ECharts = 'echarts',
}

// CDN 资源配置接口
export interface CdnResource {
  source: CdnSource
  url: string
  integrity?: string // SRI 完整性校验值
  crossorigin?: 'anonymous' | 'use-credentials' // 跨域策略
  fallbackUrls?: string[] // 备用URL
  preload?: boolean // 是否预加载
  attributes?: Record<string, string> // 自定义属性
}

// 依赖元数据接口
export interface DependencyMeta {
  version: string
  mainSource: CdnSource
  sri?: string
  minified?: boolean
  esModule?: boolean
  license?: 'MIT' | 'Apache-2.0' | string
  deprecated?: boolean
  size?: {
    gzip: number
    original: number
  }
}

// 完整依赖配置
export interface DependencyConfig {
  enabled: boolean
  builtIn: boolean
  windowProperty: string
  environment?: DependencyEnvironmentProperty // 环境属性配置
  checkMounted: boolean
  meta: DependencyMeta
  resources: CdnResource[]
  loadStrategy?: 'parallel' | 'sequential' // 加载策略
  retryPolicy?: {
    maxAttempts: number
    interval: number
  }
}
// 环境属性配置类型
export type DependencyEnvironmentProperty = SimplePropertyConfig | NamespacedPropertyConfig
// 简单属性配置（直接访问 window.property）
export interface SimplePropertyConfig {
  type: 'simple'
  property: string
}
// 命名空间属性配置（访问 window.namespace.property）
export interface NamespacedPropertyConfig {
  type: 'namespaced'
  namespace: string
  property: string
  separator?: string // 可选分隔符，默认为 '.'
}

/**
 * 依赖状态报告接口
 */
export interface DependencyStatusReport {
  dependency: ExternalDependency
  enabled: boolean
  builtIn: boolean
  loaded: boolean
  configuredVersion: string
  actualVersion: string
  versionSource: 'config' | 'runtime'
  windowProperty: string
  meta: any
}

export type DependencyConfigRecord = Record<ExternalDependency, DependencyConfig>

// 外部依赖元数据
export const DEPENDENCY_META: Record<ExternalDependency, DependencyMeta> = {
  [ExternalDependency.JQuery]: {
    version: '3.7.1',
    mainSource: CdnSource.Cdnjs,
  },
  [ExternalDependency.SweetAlert]: {
    version: '11.26.2',
    mainSource: CdnSource.Cdnjs,
  },
  [ExternalDependency.ECharts]: {
    version: '6.0.0',
    mainSource: CdnSource.Cdnjs,
    sri: 'sha256-uqjf5+HZM2uY6Jhrp+IOoV582+oe9CpZ1ZR4Yy+kWh0=',
  },
}

// 外部依赖配置
export const REQUIRE_DEPENDENCY_CONFIG: DependencyConfigRecord = {
  [ExternalDependency.JQuery]: {
    enabled: true,
    builtIn: true,
    windowProperty: 'jQuery',
    environment: {
      type: 'simple',
      property: 'jQuery',
    },
    checkMounted: false,
    meta: DEPENDENCY_META[ExternalDependency.JQuery],
    resources: [
      {
        source: CdnSource.Cdnjs,
        url: `https://cdnjs.cloudflare.com/ajax/libs/jquery/${DEPENDENCY_META[ExternalDependency.JQuery].version}/jquery.min.js`,
      },
      {
        source: CdnSource.Jsdelivr,
        url: `https://cdn.jsdelivr.net/npm/jquery@${DEPENDENCY_META[ExternalDependency.JQuery].version}/dist/jquery.min.js`,
      },
      {
        source: CdnSource.Unpkg,
        url: `https://unpkg.com/jquery@${DEPENDENCY_META[ExternalDependency.JQuery].version}/dist/jquery.min.js`,
      },
    ],
  },
  [ExternalDependency.SweetAlert]: {
    enabled: true,
    builtIn: true,
    windowProperty: 'Swal',
    checkMounted: false,
    meta: DEPENDENCY_META[ExternalDependency.SweetAlert],
    resources: [
      {
        source: CdnSource.Cdnjs,
        url: `https://cdnjs.cloudflare.com/ajax/libs/sweetalert2/${DEPENDENCY_META[ExternalDependency.SweetAlert].version}/sweetalert2.min.js`,
      },
      {
        source: CdnSource.Jsdelivr,
        url: `https://cdn.jsdelivr.net/npm/sweetalert2@${DEPENDENCY_META[ExternalDependency.SweetAlert].version}/dist/sweetalert2.all.min.js`,
      },
      {
        source: CdnSource.Unpkg,
        url: `https://unpkg.com/sweetalert2@${DEPENDENCY_META[ExternalDependency.SweetAlert].version}/dist/sweetalert2.all.min.js`,
      },
    ],
  },
  [ExternalDependency.ECharts]: {
    enabled: true,
    builtIn: false,
    windowProperty: 'echarts',
    environment: {
      type: 'simple',
      property: 'echarts',
    },
    checkMounted: false,
    meta: DEPENDENCY_META[ExternalDependency.ECharts],
    resources: [
      {
        source: CdnSource.Cdnjs,
        url: `https://cdnjs.cloudflare.com/ajax/libs/echarts/${DEPENDENCY_META[ExternalDependency.ECharts].version}/echarts.min.js`,
      },
      {
        source: CdnSource.Jsdelivr,
        url: `https://cdn.jsdelivr.net/npm/echarts@${DEPENDENCY_META[ExternalDependency.ECharts].version}/dist/echarts.min.js`,
      },
      {
        source: CdnSource.Unpkg,
        url: `https://unpkg.com/echarts@${DEPENDENCY_META[ExternalDependency.ECharts].version}/dist/echarts.min.js`,
      },
    ],
  },
}

/**
 * 统一的依赖配置获取函数
 * @param options 配置选项
 * @param options.includeBuiltIn 是否包含内建依赖
 * @param options.onlyBuiltIn 是否只获取内建依赖
 * @param options.enabledOnly 是否只获取已启用的依赖
 */
export function getDependencyConfigs(options: {
  includeBuiltIn?: boolean
  onlyBuiltIn?: boolean
  enabledOnly?: boolean
} = {}): [ExternalDependency, DependencyConfig][] {
  const {
    includeBuiltIn = false,
    onlyBuiltIn = false,
    enabledOnly = true,
  } = options

  return Object.entries(REQUIRE_DEPENDENCY_CONFIG)
    .filter(([_, config]) => {
      // 启用状态过滤
      if (enabledOnly && !config.enabled)
        return false

      // 内建依赖过滤
      if (onlyBuiltIn)
        return config.builtIn

      // 包含内建依赖过滤
      return !(!includeBuiltIn && config.builtIn)
    })
    .map(([key, config]) => [key as ExternalDependency, config])
}

/**
 * 获取所有的依赖配置
 */
export function getAllDependencyConfigs(): [ExternalDependency, DependencyConfig][] {
  return getDependencyConfigs({ includeBuiltIn: true, enabledOnly: false })
}

/**
 * 获取所有已启用的依赖配置
 */
export function getEnabledDependencyConfigs(includeBuiltIn = false): [ExternalDependency, DependencyConfig][] {
  return getDependencyConfigs({ includeBuiltIn, enabledOnly: true })
}

/**
 * 获取所有内建的依赖配置
 */
export function getBuiltInDependencyConfigs(): [ExternalDependency, DependencyConfig][] {
  return getDependencyConfigs({ onlyBuiltIn: true, enabledOnly: true })
}

/**
 * 获取依赖的元数据
 */
export function getDependencyMeta(dep: ExternalDependency): DependencyMeta {
  return REQUIRE_DEPENDENCY_CONFIG[dep].meta
}

/**
 * 获取所有依赖的主源 URL
 */
export function getAllPrimaryUrls(includeBuiltIn = false): string[] {
  const dependencyConfigs = getEnabledDependencyConfigs(includeBuiltIn)
  return dependencyConfigs.map(([dep, config]) => {
    const primarySource = config.meta.mainSource
    const primaryResource = config.resources
      .find(res => res.source === primarySource)
    const sri = config.meta.sri || primaryResource?.integrity

    if (!config.builtIn && !sri) {
      console.error(`依赖 ${dep} 没有配置 SRI`)
    }

    return primaryResource?.url ? `${primaryResource.url}${sri ? `#${sri}` : ''}` : ''
  }).filter(Boolean)
}

/**
 * 获取指定依赖的完整资源信息
 * @param config 依赖配置
 * @returns 完整的资源配置数组
 */
export function getDependencyResources(config: DependencyConfig): CdnResource[] {
  return config.resources.map((resource) => {
    // 创建资源副本，避免修改原始配置
    const enhancedResource: CdnResource = {
      ...resource,
      // 自动填充integrity（如果资源没有设置，使用 meta 中的SRI）
      integrity: resource.integrity || config.meta.sri,
      // 自动填充crossorigin（默认为anonymous）
      crossorigin: resource.crossorigin || 'anonymous',
      // 确保其他属性存在
      fallbackUrls: resource.fallbackUrls || [],
      attributes: resource.attributes || {},
    }

    return enhancedResource
  })
}
